<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Application;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Session\Config\SessionConfig;
use Zend\Session\SessionManager;
use Zend\Session\Container;
use Zend\EventManager\EventInterface;
use Zend\EventManager\EvenManagerInterface;
use Zend\ModuleManager\ModuleManager;
use Zend\EventManager\StaticEventManager;
use Zend\Debug\Debug;
use Zend\Db\Adapter\Adapter;
use Zend\Log\Logger;
use Zend\Log\Writer\FirePhp;

class Module
{

	public function init(ModuleManager $moduleManager)
	{
		//$sm = $moduleManager->getEventManager()->getSharedManager();
		//$sm->attach('application','route',array($this, 'onRoute'));
	}



	public function onBootstrap(MvcEvent $e)
	{

		$e->getApplication()->getServiceManager()->get('translator');
		$eventManager        = $e->getApplication()->getEventManager();
		$moduleRouteListener = new ModuleRouteListener();
		$moduleRouteListener->attach($eventManager);
		
		//firephp logger
// 		$logger = new \Zend\Log\Logger();
// 		$writerFirebug = new \Zend\Log\Writer\FirePhp(new \Zend\Log\Writer\FirePhp\FirePhpBridge(\FirePHP::getInstance(true)));
// 		$logger->addWriter($writerFirebug, 0);
// 		$logger->registerErrorHandler($logger);
// 		$logger->registerExceptionHandler($logger);
// 		$logger->info('Firephp logger initilized'.__FILE__.__LINE__);
// 		register_shutdown_function(function () use ($logger)
// 		{
// 			if ($e = error_get_last()) {
// 				$logger->ERR($e['message'] . " in " . $e['file'] . ' line ' . $e['line']);
// 				$logger->__destruct();
// 			}
// 		});
			
		$config = $e->getApplication()
		->getServiceManager()
		->get('Configuration');

		$sessionConfig = new SessionConfig();
		$sessionConfig->setOptions($config['session']);
		$sessionManager = new SessionManager($sessionConfig);
		$sessionManager->start();

		Container::setDefaultManager($sessionManager);

			
		//acl
		$this -> initAcl($e);
		$e -> getApplication() -> getEventManager() -> attach('route', array($this, 'checkAcl'));
		$e -> getApplication() -> getEventManager() -> attach('route', array($this, 'onRoute'));


	}

	public function onRoute(MvcEvent $e){
		//$e -> getApplication() -> getEventManager() -> attach('route', array($this, 'checkLoginStatus'));
		$auth = $e-> getApplication() ->getServiceManager()->get('zfcuser_auth_service');
		//var_dump($e->getRouteMatch()->getParam('controller'));
		if (!$auth->hasIdentity() && $e->getRouteMatch()->getParam('controller') != 'zfcuser') {
			$e->getRouteMatch()->setParam('controller', 'zfcuser');
			$e->getRouteMatch()->setParam('action', 'login');
		}
	}


	public function getConfig()
	{
		return include __DIR__ . '/config/module.config.php';
	}

	public function getAutoloaderConfig()
	{
		return array(
				'Zend\Loader\ClassMapAutoloader' => array(
						__DIR__ . '/autoload_classmap.php',
				),
				'Zend\Loader\StandardAutoloader' => array(
						'namespaces' => array(
								__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
						),
				),
		);
	}

	public function getViewHelperConfig(){
		return array(
				'invokables' => array(
						'ChatHelper' => 'Application\View\Helper\ChatHelper'
				)
		);
	}

	public function initAcl(MvcEvent $e) {

		$acl = new \Zend\Permissions\Acl\Acl();
		$roles = include __DIR__ . '/config/module.acl.roles.php';
		$allResources = array();
		foreach ($roles as $role => $resources) {

			$role = new \Zend\Permissions\Acl\Role\GenericRole($role);
			$acl -> addRole($role);

			$allResources = array_merge($resources, $allResources);

			//adding resources
			foreach ($resources as $resource) {
				// Edit 4
				if(!$acl ->hasResource($resource))
					$acl -> addResource(new \Zend\Permissions\Acl\Resource\GenericResource($resource));
			}
			//adding restrictions
			foreach ($allResources as $resource) {
				$acl -> allow($role, $resource);
			}
		}
		//testing
		//var_dump($acl->isAllowed('guest','add-user'));
		//true

		//setting to view
		$e -> getViewModel() -> acl = $acl;

	}

	public function checkAcl(MvcEvent $e) {
		$route = $e -> getRouteMatch() -> getMatchedRouteName();
		//you set your role
		$userRole = 'admin';
		//var_dump($route);
		if ($e -> getViewModel() -> acl ->hasResource($route) && !$e -> getViewModel() -> acl -> isAllowed($userRole, $route)) {
			$response = $e -> getResponse();
			//location to page or what ever
			$response -> getHeaders() -> addHeaderLine('Location', $e -> getRequest() -> getBaseUrl() . '/accessDenied');
			//$this->redirect()->toUrl('user/login');
			$response -> setContent("Access denied");
			$response -> setStatusCode(303);

		}
	}

	public function checkLoginStatus(MvcEvent $e){

	}

}
